import qs from "qs";
interface GeogleConfig {
	/**
	 * Google OAuth 客户端 ID
	 */
	clientId: string;
	/**
	 * Google OAuth 客户端密钥
	 */
	clientSecret: string;
	/**
	 * 重定向 URI
	 */
	redirectUri: string;
	/**
	 * 请求的权限范围，可以根据需求修改
	 */
	scope: string;
	/**
	 * 用于防止跨站请求伪造（CSRF）攻击，可以不设置，可以随心设置
	 */
	state: string;
	/**
	 * 授权响应类型，表示要求返回授权码
	 */
	responseType: string;
	grantType: string;
	code?: string;
}
export interface GeogleResponse {
	code: number;
	data?: any;
	message?: string;
}
const useGeogleLogin = () => {
	const loginConfig: GeogleConfig = {
		clientId:
			"877400931414-gjvdb2p27ra3oq3kl3n8ld82ci71cnbp.apps.googleusercontent.com",
		redirectUri: "http://localhost:2800/pages/login/index",
		scope: "email profile",
		state: "",
		responseType: "code",
		clientSecret: "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",
		grantType: "authorization_code",
		code: "",
	};
	const oauth2 = () => {
		const url = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${loginConfig.clientId}&redirect_uri=${loginConfig.redirectUri}&scope=${loginConfig.scope}&state=${loginConfig.state}&response_type=${loginConfig.responseType}`;
		window.location.href = url;
	};
	const getUserInfo = (): Promise<GeogleResponse> => {
		return new Promise((resolve, reject) => {
			const { code } = qs.parse(window.location.search.split("?")[1]);
			// const urlParams = new URLSearchParams(window.location.search);
			// const code = urlParams.get("code");
			if (!code) {
				resolve({
					code: 401,
					message: "未获取到授权码",
				});
				return;
			}
			// 用授权码交换访问令牌地址
			const tokenEndpoint = "https://oauth2.googleapis.com/token";
			const requestBody = new URLSearchParams();
			requestBody.append("code", code);
			// 你的 Google OAuth 客户端 ID
			requestBody.append("client_id", loginConfig.clientId);
			// 你的Google OAuth 客户端密钥
			requestBody.append("client_secret", loginConfig.clientSecret);
			requestBody.append("redirect_uri", loginConfig.redirectUri);
			requestBody.append("grant_type", loginConfig.grantType);

			fetch(tokenEndpoint, {
				method: "POST",
				headers: {
					"Content-Type": "application/x-www-form-urlencoded",
				},
				body: requestBody,
			})
				.then((response) => response.json())
				.then((data) => {
					// 获得token令牌的信息
					const accessToken = data.access_token;
					// 调用获取用户信息接口
					fetch("https://www.googleapis.com/oauth2/v2/userinfo", {
						headers: {
							Authorization: `Bearer ${accessToken}`,
						},
					})
						.then((response) => response.json())
						.then((userInfo) => {
							// 获取用户信息
							resolve({
								code: 200,
								data: userInfo,
							});
						});
				});
		});
	};
	return {
		oauth2,
		getUserInfo,
	};
};
export { useGeogleLogin };
export default useGeogleLogin;
